
#include "luac.h"
#include "ports/port.h"
#include "luas.h"



Luac LUAC;
 
static int port_on_accept(int portfd, int sockfd);
static int port_on_packet(int portfd, int linefd, int msgid, int pktfd);


int luac_new_port()
{
    int portfd = port_new();
    
    port_set_userdata(portfd, (void *)0);
    port_set_cb_accept(portfd, port_on_accept);
    port_set_cb_packet(portfd, port_on_packet);
    return portfd;
}

int luac_load_modules(const char *dirpath)
{
    return mod_mgr_load_modules(dirpath);
}



static void luac_new()
{
    LUAC.msg_map = dictCreate(&dictTypeNone, "msg_map");
}
 
 
static int port_on_packet(int portfd, int linefd, int msgid, int pktfd)
{   
    js_sys("jings", "port_on_packet\n");
    mod_mgr_dispatch(linefd, msgid, pktfd);
} 

static int port_on_accept(int portfd, int sockfd)
{   

    int fd = port_accept(portfd, sockfd);
    
}




static int New(lua_State *L)
{
    if (LUA_ARGNUM == 0)
    {
        luac_new();
    }
    LUA_RETURN(0);
}

static int NewPort(lua_State *L)
{
    if (LUA_ARGNUM == 0)
    {
        int portfd = luac_new_port();
        LUA_RETURN(portfd);
    }
    LUA_RETURN(-1);
}
static int LoadModules(lua_State *L)
{
    if (LUA_ARGNUM == 1 && LUA_ISSTRING(1))
    {
        char *dirpath = (char*)LUA_TOSTRING(1);

        int modfd = luac_load_modules(dirpath);
        LUA_RETURN(modfd);
    }

    LUA_RETURN(-1);
}


static int InsertLuaTimer(lua_State *L)
{

    if (LUA_ARGNUM == 3 
    && LUA_ISNUMBER(1)&& LUA_ISNUMBER(2) && LUA_ISSTRING(3))
    {

        int msgid        = (int)LUA_TONUMBER(1);
        int msec          = (int)LUA_TONUMBER(2);
        const char *funcname          = (const char *)LUA_TOSTRING(3);
        
        int rt = mod_mgr_insert_lua_timer(msgid, msec,funcname);

        LUA_RETURN(rt);
    }

    LUA_RETURN(0);
}
static int InsertLuaFunc(lua_State *L)
{

    if (LUA_ARGNUM == 2 && LUA_ISNUMBER(1)&& LUA_ISSTRING(2))
    {
        int msgid        = (int)LUA_TONUMBER(1);
        const char *funcname          = (const char *)LUA_TOSTRING(2);
        
        int rt = mod_mgr_insert_lua_func(msgid, funcname);

        LUA_RETURN(rt);
    }

    LUA_RETURN(0);
}


static luaL_Reg lua_lib[] = 
{
	LUA_FUNC_INIT(New),
    LUA_FUNC_INIT(NewPort),
    LUA_FUNC_INIT(LoadModules),
    LUA_FUNC_INIT(InsertLuaTimer),
    LUA_FUNC_INIT(InsertLuaFunc),
    {NULL, NULL}
};

int luac_init()
{
    luas_reg_lib("LUAC", lua_lib);
}

